import fetch from 'node-fetch'
import AbortController from 'abort-controller'
import { decode } from './charset'

// instance.interceptors.response.use(function (response) {
//   // Do something with response data
//   return response.data
// }, function (error) {
//   // Do something with response error
//   return Promise.reject(error)
// })

async function request (url: string, config: any, source?: any) {
  const options = { ...config }

  const controller = new AbortController()
  const timeout = setTimeout(() => {
    controller.abort()
  }, 3000)

  options.signal = controller.signal

  // 强制arraybuffer 后面检测编码
  try {
    const response = await fetch(url, options)
    if (config && config.charset) {
      const data = await response.buffer()
      return decode(data, config.charset)
    }
    // const data = res.data.toString()
    // // 应该足够了
    // const regex = /charset="?gbk"?/i
    // if (regex.test(data)) {
    //   return decode(res.data, 'gbk')
    // }
    return response.text()
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('request was aborted')
    }
    throw error
  } finally {
    clearTimeout(timeout)
  }
}

function get (url: string, params: any = {}, source?: any) {
  return request(url, {
    method: 'GET',
    params
  }, source)
}
function post (url: string, data: string, source?: any) {
  return request(url, {
    method: 'POST',
    data
  }, source)
}

export {
  get,
  post,
  request
}
